package com.woniuxy.background.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniuxy.background.advice.SysLog;
import com.woniuxy.background.common.RestResult;
import com.woniuxy.background.dao.AdminMapper;
import com.woniuxy.background.dto.MenuDTO;
import com.woniuxy.background.exception.MenusServiceException;
import com.woniuxy.background.pojo.Admin;
import com.woniuxy.background.pojo.Menu;
import com.woniuxy.background.service.MenusService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/menu")
public class MenuController {

    @Autowired
    private MenusService menuService;
    @Autowired
    private AdminMapper adminMapper;


    /**
     * 加载导航菜单
     * @return
     */
    @GetMapping("/getMenus")
    @ResponseBody
    @RequiresPermissions("sys:menu:list")
    public List<MenuDTO> getMenus(){
        Admin admin = adminMapper.findByName( SecurityUtils.getSubject().getPrincipal().toString());
        //Admin admin = (Admin) SecurityUtils.getSubject().getPrincipal();
        List<MenuDTO> menus = menuService.findByAdmin(admin);

        return menus;
    }

    /**
     * 加载权限树的数据
     * @return
     */
    @GetMapping("/loadTree")
    @ResponseBody
    public String loadTree(){
        List<Menu> menus = menuService.findAll();
        //将menus集合转换为JSON字符串
        ObjectMapper mapper = new ObjectMapper();
        try {
            String jsonStr = mapper.writeValueAsString(menus);
            return jsonStr;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return null;
        }
    }


    //加载权限tree的数据
    @GetMapping("/loadCheckedTree/{roleId}")
    @ResponseBody
    public String loadCheckedTree(@PathVariable("roleId") int roleId){
        List<Menu> menu = menuService.findCheckMeuns(roleId);
        ObjectMapper mapper = new ObjectMapper();
        try {
            String jsonStr = mapper.writeValueAsString(menu);
            return jsonStr;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return null;
        }
    }




    @GetMapping("/loadMenus")
    @ResponseBody
    public Map loadMenus(){
        List<Menu> list= menuService.findAll();
        Map result = new HashMap();
        result.put("code",0);
        result.put("msg","success");
        result.put("data",list);
        return result;
    }

    @RequestMapping("/addMenu/{parentId}")
    public String addMenu(@PathVariable("parentId") int parentId, Model model){
        model.addAttribute("parentId",parentId);
        return "/sys/addMenu";
    }
    @RequestMapping("/toEditMenu/{menuId}")
    public String toEditMenu(@PathVariable("menuId") int menuId, Model model){
        Menu menu = menuService.selectByPrimaryKey(menuId);
        model.addAttribute("menu",menu);
        return "/sys/editMenu";
    }

    @PostMapping("/saveMenu")
    @ResponseBody
    @SysLog(value = "添加目录")
    @RequiresPermissions("sys:menu:save")
    public RestResult saveMenu(Menu menu){
        System.out.println(menu);
        //检查同级节点下节点的名称不能重复
        if(menuService.checkMenuName(menu)){
            return RestResult.failed("同级节点下节点名称不能重复");
        }
        try {
            menuService.saveMeuns(menu);
        } catch (Exception e) {
            e.printStackTrace();
            return RestResult.failed("添加失败");
        }
        return RestResult.success();
    }

    @PostMapping("/updateMenu")
    @ResponseBody
    @SysLog(value = "更新目录")
    @RequiresPermissions("sys:menu:update")
    public RestResult updateMenu(Menu menu){

        //检查同级节点下节点的名称不能重复
        if(menuService.checkMenuName(menu)){
            return RestResult.failed("同级节点下节点名称不能重复");
        }
        try {
            menuService.updateByPrimaryKeySelective(menu);
        } catch (Exception e) {
            e.printStackTrace();
            return RestResult.failed("添加失败");
        }
        return RestResult.success();

    }

    @PutMapping("/updateMenuSorting")
    @ResponseBody
    @SysLog(value = "更新排序")
    @RequiresPermissions("sys:menu:update")
    public RestResult updateMenuSorting(int menuId, int sorting){
        try {
            menuService.updateSorting(menuId,sorting);
            return RestResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return RestResult.failed("更新排序失败");
        }
    }

    @DeleteMapping("/delete/{id}")
    @ResponseBody
    @SysLog(value = "删除目录")
    @RequiresPermissions("sys:menu:delete")
    public RestResult delete(@PathVariable("id")int id){
        if(menuService.checkChildrenNode(id)){
            return RestResult.failed("该节点下存在子节点不能删除");
        }
        try {
            menuService.removeMenus(id);
        } catch (MenusServiceException e) {
            e.printStackTrace();
            return RestResult.failed(e.getMessage());
        }catch (Exception e) {
            e.printStackTrace();
            return RestResult.failed("删除失败");
        }
        return RestResult.success();
    }

























}
